<?php

//  store.php
//  Memento 3.0
//
//  Created by Christopher Burrows on 10-07-28
//  Copyright 2010 Team Memento. All rights reserved.
//
//    Description:
//  Uploads a Memory to the server. All files (jpg and caf)
//  are limited to 1024 KB.
//
//  10-07-28: File created. (C. Burrows)
//
//  HTML POST Fields:
//  'session_token' (string)
//  'memory_id'     (int)
//  'memory_time'   (date-time)
//  'latitude'      (double)
//  'longtitude'    (double)
//
//  OUTPUT:
//  Line 1: Session validation  (bool)
//  Line 2: Image uploaded      (bool)
//  Line 3: Audio uploaded      (bool)

include ($_SERVER['DOCUMENT_ROOT'].'/functions.php');

connect_to_database();

$validation_success = 0;
$image_uploaded = 0;
$audio_uploaded = 0;

// Check that the provided session token is valid
$session_token = $_POST['session_token'];
$memory_id = $_POST['memory_id'];
$memory_time = $_POST['memory_time'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];

if (validate_session_token($session_token)) {
    
    $validation_success = 1;
    
    // Get the collection_id
    $result = mysql_query("SELECT * FROM sessions WHERE
            session_token='$session_token'");
    $row = mysql_fetch_array($result);
    $collection_id = $row['collection_id'];
          
    // Upload the image and audio files
    $uploaddir = '/home/mementof/memento.freehostingcloud.com/upload/'.$collection_id;
    
    $imagefile = '/'.$memory_id.'.jpg';
    $audiofile = '/'.$memory_id.'.caf';
    
    if (!is_dir($uploaddir))
        mkdir($uploaddir, 0744);
    
    if (move_uploaded_file($_FILES['image_file']['tmp_name'],
            $uploaddir.$imagefile))
        $image_uploaded = 1;
        
    if (move_uploaded_file($_FILES['audio_file']['tmp_name'],
            $uploaddir.$audiofile))
        $audio_uploaded = 1;
    
    $time = strtotime($memory_time); //date("Y-m-d H:i:s O", $memory_time);
    
    // Create a new Memory record
    $id = $collection_id.'-'.$memory_id;
    mysql_query("INSERT INTO memories (id, collection_id, memory_id, memory_time, latitude, longitude) VALUES ('$id', '$collection_id',
            '$memory_id', '$time', '$latitude', '$longitude')");
    
    echo $validation_success.PHP_EOL;
    echo $image_uploaded.PHP_EOL;
    echo $audio_uploaded.PHP_EOL;
}
    
?>